package cn.eweb.ttkt;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EncodingUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.provider.Settings.Secure;
import android.util.Log;

public class SplashActivity extends Activity {
	
	private Handler handler = new Handler() {  
        public void handleMessage(Message msg) { 
        	switch(msg.what){
        	case 0:
        		showShotCutMessage();
        		break;
        	case 1:
        		Intent intent = new Intent(Intent.ACTION_MAIN);  
                intent.setClass(SplashActivity.this, MainTab.class);  
                SplashActivity.this.startActivity(intent);
                SplashActivity.this.finish();	
        		break;
        	}
        }  
    };
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);
        new Thread() {
			@Override
			public void run() {
		        startPushService();
		        if(!isSetShotCut()){
		        	handler.sendEmptyMessage(0);
		        }else{
		        	handler.sendEmptyMessageDelayed(1, 1000);
		        }
			}
        }.start();
    }
    
    private void startPushService(){
    	SharedPreferences p = getSharedPreferences(PushService.TAG, MODE_PRIVATE);
  	  	boolean started = p.getBoolean(PushService.PREF_STARTED, false);
  	  	if(!started){
  	  		final String deviceId = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
	  	  	Editor editor = p.edit();
	    	editor.putString(PushService.PREF_DEVICE_ID, deviceId);
	    	editor.commit();
	    	new Thread() {
				@Override
				public void run() {
					super.run();
					try {  
			            // 定义获取文件内容的URL
						String push_url = getString(R.string.device_register_url)+"&device="+deviceId;
				    	URL myURL = new URL(push_url);  
			            // 打开URL链接  
			            URLConnection ucon = myURL.openConnection();
			            // 使用InputStream，从URLConnection读取数据  
			            InputStream is = ucon.getInputStream();  
			            BufferedInputStream bis = new BufferedInputStream(is);  
			            // 用ByteArrayBuffer缓存  
			            ByteArrayBuffer baf = new ByteArrayBuffer(50);  
			            int current = 0;  
			            while ((current = bis.read()) != -1) {  
			                baf.append((byte) current);  
			            }  
			            // 将缓存的内容转化为String,用UTF-8编码  
			            String result = EncodingUtils.getString(baf.toByteArray(), "UTF-8");
			            Log.e("test", result);
			        } catch (Exception e) {  
			            e.printStackTrace();
			        }  
				}
			}.start();
			PushService.actionStart(getApplicationContext());
  	  	}
    }
    
    /**
	 * 是否设置桌面快捷方式
	 * @return
	 */
	private boolean isSetShotCut(){
		SharedPreferences sp = getSharedPreferences("setting",Context.MODE_PRIVATE);
		if(sp.getString("SHOTCUT", null)==null){
			return false;
		}else{
			if(sp.getString("SHOTCUT", null).equals("1")){
				return true;
			}else{
				return false;
			}
		}
	}
    
    /**
	 * 展示添加桌面快捷图标信息
	 */
	public void showShotCutMessage(){
		AlertDialog.Builder ad = new AlertDialog.Builder(this);
		ad.setIcon(android.R.drawable.ic_dialog_info);
		ad.setTitle(getString(R.string.notice)); 
        ad.setMessage(getString(R.string.shot_cut_content));
        ad.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
				//保存设置信息
				saveShutCutSetting("1");
				//添加快捷方式
				addShotCut();
				//进入下个页面
				handler.sendEmptyMessage(1);
			}
               
        });  
        ad.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				//保存设置信息
				saveShutCutSetting("0");
				dialog.cancel();
				//进入下个页面
				handler.sendEmptyMessage(1);
			}
               
        });
        AlertDialog alert = ad.create();
        alert.show();
	}
    
    // much easier to handle key events   
    @Override  
    public void onBackPressed() {  
    }
	
	private void saveShutCutSetting(String result){
		SharedPreferences sp = getSharedPreferences("setting",Context.MODE_PRIVATE);
		Editor ed = sp.edit();
		ed.putString("SHOTCUT", result);
		ed.commit();
	}
	
	private void addShotCut(){
		Intent shortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT"); 
		//不允许重复创建  
	    shortcutIntent.putExtra("duplicate", false);  
		//添加名称
	    shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name)); 
		
	    //快捷图片  
	    Parcelable icon = Intent.ShortcutIconResource.fromContext(  
	            getApplicationContext(), R.drawable.icon);
	    shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);  
	    
	    Intent intent = new Intent(getApplicationContext(),SplashActivity.class);
	    //下面两个属性是为了当应用程序卸载时桌面 上的快捷方式会删除  
        intent.setAction("android.intent.action.MAIN");  
        intent.addCategory("android.intent.category.LAUNCHER");  
	    //点击快捷图片，运行的程序主入口  
	    shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
		sendBroadcast(shortcutIntent);
	}
}